<?php

// http://www.php.net/manual/en/function.gzdecode.php#84174
function softcoded_gzdecode($data){
    $g=tempnam('./','gz');
    file_put_contents($g,$data);
    ob_start();
    readgzfile($g);
    $d=ob_get_clean();
    unlink($g);
    return $d;
}

$time_start = time();

$csv_gz_data = file_get_contents("http://software77.net/geo-ip/?DL=1");
$csv_data = softcoded_gzdecode($csv_gz_data);
file_put_contents("/tmp/ip2country.csv",$csv_data);

$time_finish_download = time();

try {
    //open the database
    $db = new PDO('sqlite:Counter.db');

    //create the database
    $db->exec("CREATE TABLE IpRanges (Id INTEGER PRIMARY KEY, RangeStart INTEGER, RangeEnd INTEGER, CountryCode TEXT)");

    echo 'Database and Table created sucessfully.<br />';

    $db->beginTransaction();
    $db->exec("DELETE FROM IpRanges");

    echo 'Removed old ranges.<br />';

    $inserts = 0;
    if (($handle = fopen("/tmp/ip2country.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $start = $data[0];
            $end = $data[1];
            $country = $data[4];
            $db->exec("INSERT INTO IpRanges (RangeStart, RangeEnd, CountryCode) VALUES(" . $start . "," . $end . ",'" . $country . "')");
            $inserts++;
        }
        fclose($handle);
    }
    $db->commit();

    echo 'Inserted ' . $inserts . ' ranges.';

    // close the database connection
    $db = NULL;
} catch(PDOException $e) {
    print 'Exception : '.$e->getMessage();
}

unlink("/tmp/ip2country.csv");

$time_finish = time();

echo "<br />";
echo "Started at: " . $time_start . "<br />";
echo "Download finished at: " . $time_finish_download . " (" . ($time_finish_download - $time_start) . ")<br/>";
echo "Finished at: " . $time_finish . " (" . ($time_finish - $time_start) . ")";
